using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Core;

namespace Forum.Business
{
    public class ThreadList : ForumUserControl,
        IReplyConverter<ThreadReply, GetListOperation>
    {
        protected Repeater list;
        protected Pager pager;
        protected CurrentPage currentPage;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            if (!Page.IsPostBack && !AjaxManager.IsCallBack)
            {
                requestBinders.Add(RequestHelper.BuildGetThreadListRequest(this, pager.PageSize));
            }
        }


        protected override void OnLoad(EventArgs e)
        {
            AjaxManager.Register(this, "AjaxMethod");
        }

        private void BindData(ThreadReply reply)
        {
            if (list == null)
            {
                return;
            }

            list.DataSource = reply.EntityList;
            list.DataBind();

            if (pager != null && currentPage != null)
            {
                pager.TotalPages = pager.CalculateTotalPages(reply.TotalRecords);
                currentPage.TotalRecords = reply.TotalRecords;
                currentPage.TotalPages = pager.TotalPages;
                currentPage.PageIndex = pager.PageIndex;
            }
        }

        #region Ajax Method

        [AjaxMethod]
        public void DeleteThread(int threadId)
        {
            if (!ValidatePermission(PermissionType.DeleteThread))
            {
                throw new Exception("Operation denied.");
            }
            BusinessManager.DeleteThread(threadId);
        }

        [AjaxMethod]
        public void DeleteThreads(string threadIds)
        {
            if (string.IsNullOrEmpty(threadIds))
            {
                return;
            }
            string[] threadIdArray = threadIds.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            int threadId = 0;
            foreach (string stringThreadId in threadIdArray)
            {
                try
                {
                    threadId = Int32.Parse(stringThreadId);
                }
                catch
                {
                    continue;
                }
                if (threadId > 0)
                {
                    DeleteThread(threadId);
                }
            }
        }

        #endregion

        #region IReplyConverter<ThreadReply,GetListOperation> Members

        public void ConvertReply(ThreadReply reply, GetListOperation operation)
        {
            if (reply != null)
            {
                BindData(reply);
            }
        }

        #endregion
    }
}